<?php

namespace app\common\model;

use think\Model;
use think\Db;
/**
 * 地址模型
 */
class Address extends Model
{
	protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            if($row->is_default == '1'){
            	$row->getQuery()->where(['user_id' => $row->user_id])->update(['is_default' => '0']);
            	$row->getQuery()->where(['id' => $row->id])->update(['is_default' => '1']);

            }
        });

        self::afterUpdate(function($row){

        	if($row->is_default == '1'){
        		$row->getQuery()->where(['user_id' => $row->user_id])->update(['is_default' => '0']);
        		$row->getQuery()->where(['id' => $row->id])->update(['is_default' => '1']);

        	}
        });


    }

    public function getUserAddressList($user_id){
	    $data = Db::name('address')->where(['user_id' => $user_id])->order('id desc,is_default desc')->select();
	    return $data;
    }

}